import { _decorator, Component, EditBox, RichText, Node, Label, Button, JsonAsset } from 'cc';
import { List } from '../Basic/Component/List';
import { autoComp, rootNode } from '../Basic/Manager/BaseManager';
import { DataMgr } from '../Basic/Manager/DataManager';
const { ccclass, property } = _decorator;

@ccclass('RichTextEditor')
export class RichTextEditor extends Component {
  @property(EditBox)
  editBox: EditBox | null = null;

  @property(RichText)
  richTextField: RichText | null = null;

  @property(Node)
  editBtnNode: Node | null = null;

  @autoComp(List)
  list: List;

  @property(JsonAsset)
  jsonData: JsonAsset;

  private currentText: string = '';

  protected onEnable(): void {
    this.refreshList();
  }

  refreshList() {
    this.list.enabled = false;
    const data = [];
    this.jsonData.json.forEach((element) => {
      data.push(element);
    });
    this.list.setData(data);
    this.list.enabled = true;
  }

  start() {
    if (this.editBox) {
      this.editBox.node.on('text-changed', this.onTextChanged, this);
    }

    if (this.editBtnNode) {
      this.setupButtons();
    }
  }

  onTextChanged(event: any) {
    //从editBox获取文本
    const text = this.editBox ? this.editBox.string : '';
    this.currentText = text;
    this.updateRichText();
  }

  updateRichText() {
    if (!this.richTextField) return;

    let formattedText = this.currentText.replace(/\[(.*?)\]/g, '<b>$1</b>');

    this.richTextField.string = formattedText;
  }

  setupButtons() {
    if (!this.editBtnNode) return;

    this.editBtnNode.children.forEach((buttonNode) => {
      const buttonComponent = buttonNode.getComponent(Button);

      if (buttonComponent) {
        const labelNode = buttonNode.getChildByName('EditLabel');
        const labelComponent = labelNode?.getComponent(Label);

        if (labelComponent) {
          buttonComponent.node.on(
            'click',
            () => {
              const buttonText = labelComponent.string;
              if (this.editBox) {
                this.editBox.string += buttonText;
              }
            },
            this
          );
        }
      }
    });
  }
}
